<template>
  <div class="list-common-table">
    <!-- 搜索部分 -->
    <t-form v-if="searchParams && searchParams.length" ref="form" :data="formData" :label-width="80" colon @reset="onReset" @submit="onSearch">
      <t-row>
        <t-col :span="10">
          <t-row :gutter="[24, 24]">
              <t-col :span="4" v-for="(item, index) in searchParams" :key="index">
              <t-form-item :label="item.label" :name="item.key" v-if="!item.hide">
                <t-input v-if="item.valueType !== 'select'" :value="item?.defaultValue" v-model="formData[`${item.key}`]" clearable />
                <t-select v-else v-model="formData[`${item.key}`]" :options="item.options" clearable />
              </t-form-item>
            </t-col>
          </t-row>
        </t-col>
        <t-col :span="2" class="operation-container">
          <t-button theme="primary" type="submit" :style="{ marginLeft: 'var(--td-comp-margin-s)' }">
            {{ "查询" }}
          </t-button>
          <t-button type="reset" variant="base" theme="default">
            {{ '重置' }}
          </t-button>
        </t-col>
      </t-row>
    </t-form>
    <t-row style="padding: 10px 10px">
      <!-- 新增部分 -->
      <slot name="tableHeader"></slot>
    </t-row>
    <div class="table-container">
      <t-enhanced-table 
        v-if="tree" 
        :tree="treeConfig"
        :data="data"
        :columns="COLUMNS"
        :key="'enhanced-table'"
        :selected-row-keys="selectedRowKeys"
        @select-change="onSlectedRowKeys"
        :pagination="pagination"
        :loading="loading"
        @page-change="PageChange"/>
      <t-table
        v-else
        :data="data"
        :columns="COLUMNS"
        :row-key="rowKey"
        :max-height="500"
        :selected-row-keys="selectedRowKeys"
        @select-change="onSlectedRowKeys"
        :pagination="pagination"
        :loading="loading"
        @page-change="PageChange"
      />
    </div>
  </div>
</template>

<script setup lang="ts">
import { FormInstanceFunctions, PageInfo, PaginationProps, TableTreeConfig, TreeProps } from 'tdesign-vue-next';
import { ref, PropType, defineComponent, onMounted } from 'vue';
import { SearchParamsProps } from './type/index';

const form = ref<FormInstanceFunctions>(null);
const formData = ref<Record<string, any>>({});
const selectedRowKeys = ref([]);
const data = ref<any[]>([]);
const loading = ref(false);

const props = defineProps({
  searchParams: {
    type: Array as PropType<SearchParamsProps[]>,
    required: true
  },
  COLUMNS: {
    type: Array as PropType<any[]>,
    required: true
  },
  rowKey: {
    type: String,
    default: 'id'
  },
  pagesizes: {
    type: Array as PropType<(number | { label: string; value: number })[]>,
    default: () => [10, 20, 30, 40]
  },
  asyncFc:{
    type: Function,
  },
  page: {
    type: Boolean,
    default: true
  },
  //树形结构表格封装,先判断是否为树形结构
  tree:{
    type: Boolean,
    default: false
  },
  //树形结构的配置项
  treeConfig:{
    type: Object as PropType<TableTreeConfig>,
    default: {childrenKey: 'children'}
  },

});

// 组件初始化进来，判断是否存在表单默认值
if (props.searchParams && props.searchParams.length) {
  
  const data: Record<string, any> = {}; // 明确指定 data 的类型
  //迭代表单项
  props.searchParams.forEach(item => {
    //如果存在默认值
    if (item.defaultValue || item.defaultValue == 0) {
      //将表单项value-v-vmodel赋值
      data[item.key] = item.defaultValue;
    }
  });
  formData.value = data;
}

const pagination = ref<PaginationProps>(props.page ?{
  defaultPageSize: 10,
  total: 0,
  defaultCurrent: 1,
  pageSizeOptions: props.pagesizes as (number | { label: string; value: number })[]
} :null);

const findData = async (pageNo: number, pageSize: number, params: any) => {
  loading.value = true;
  try {
    const response = await props.asyncFc(props.page ? { pageNo, pageSize, params } : params);
    if (response && response.records) {
      if (props.page) {
        data.value = response.records;
        if(response.total == 0){
          pagination.value =undefined;
        }else{
          pagination.value = {
            defaultCurrent:1,
            defaultPageSize:10,
            pageSizeOptions:props.pagesizes,
            ...pagination.value,
            total: response.total,
          }
        }
      }
    } else {
      console.error('响应数据格式不正确:', response);
    }
  } catch (e) {
    console.error('请求失败:', e);
  } finally {
    loading.value = false;
  }
};


const PageChange = ({ current, pageSize }: PageInfo) => {
  // 处理分页变化的逻辑
  findData(current, pageSize,formData.value);
};

onMounted(() => {
  findData(pagination.value?.defaultCurrent, pagination.value?.defaultPageSize,formData.value);
});
// 重置表单
const onReset = () => {
  form.value?.reset();
  findData(pagination.value?.defaultCurrent, pagination.value?.defaultPageSize,{});
};

const onSlectedRowKeys = (value: any) => {
  console.log(value);
  selectedRowKeys.value = value;
};

// 搜索
const onSearch = (params?: any) => {
  findData(pagination.value?.defaultCurrent || 1, pagination.value?.defaultPageSize || 10,formData.value);
};

//子组件暴露给父组件调用的方法
defineExpose({onSearch,getSelectedKeys:()=>selectedRowKeys.value});
</script>

<style lang="less" scoped>
.list-common-table {
  background-color: var(--td-bg-color-container);
  padding: var(--td-comp-paddingTB-xxl) var(--td-comp-paddingLR-xxl);
  border-radius: var(--td-radius-medium);

  .table-container {
    margin-top: var(--td-comp-margin-xxl);
  }

  .form-item-content {
    width: 100%;
  }

  .operation-container {
    display: flex;
    justify-content: flex-end;
    align-items: center;

    .expand {
      .t-button__text {
        display: flex;
        align-items: center;
      }
    }
  }

  .payment-col {
    display: flex;

    .trend-container {
      display: flex;
      align-items: center;
      margin-left: var(--td-comp-margin-s);
    }
  }
}
</style>

<script lang="ts">
export default defineComponent({
  name: 'STable'
});
</script>